package com.huangmb.anymark.app.net;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author hmb
 * @version 1.0
 * @since 2016/4/16 15:57
 */
public class RequestManager {
    private final List<HttpRequest> waitingTaskList = new ArrayList<>();
    private final List<HttpRequest> runningTaskList = new ArrayList<>();
    private int maxRunningTaskSize = 3;
    private static RequestManager instance;
    private CookieManager mCookieManager;

    private ExecutorService executorService;
    private static final Object lock = new Object();

    private RequestManager() {
        mCookieManager = new CookieManager();
        CookieHandler.setDefault(mCookieManager);

        int core = Runtime.getRuntime().availableProcessors();
        maxRunningTaskSize = core;
        executorService = Executors.newFixedThreadPool(core + 1);//预留给一个用于紧急任务
    }

    public static RequestManager getInstance() {
        if (instance == null) {
            synchronized (lock) {
                if (instance == null) {
                    instance = new RequestManager();
                }
            }
        }
        return instance;
    }

    public CookieManager getCookieManager() {
        return mCookieManager;
    }

    public void addTask(HttpRequest request) {
        addTask(request, false);
    }

    public void addTask(HttpRequest request, boolean isImmediately) {
        if (isImmediately || runningTaskList.size() < maxRunningTaskSize) {
            execute(request);
            return;
        }
        waitingTaskList.add(request);
    }


    public void removeTask(HttpRequest request) {
        if (request == null) {
            return;
        }
        //尝试从执行列表中移除
        runningTaskList.remove(request);

        //尝试中从等待列表中移除
        waitingTaskList.remove(request);

        request.cancel();

        tryExecuteNextTask();
    }

    public synchronized void cancelAllRequest() {
        //停止正在进行的任务
        for (final HttpRequest task : runningTaskList) {
            task.cancel();
        }

        //清空任务列表
        waitingTaskList.clear();
        runningTaskList.clear();
    }

    private void tryExecuteNextTask() {
        if (runningTaskList.size() >= maxRunningTaskSize) {
            return;
        }
        if (!waitingTaskList.isEmpty()) {
            HttpRequest request = waitingTaskList.remove(0);
            execute(request);
        }

    }

    private void execute(HttpRequest request) {
        runningTaskList.add(request);
        executorService.execute(request);
    }
}
